package com.jiyun.fiter;
/*
 * @Author:limengyao
 * @Date:2023-08-22 11:08
 * @Filename:MyFiter
 *
 */

import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyFiter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (path.contains("/userlogin")){
            return chain.filter(exchange);
        }else{
            String token = getToken(request);
            if(StringUtils.isBlank(token)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return  response.setComplete();
            }else{
                try {
                    boolean verify = JWTUtil.verify(token, "123".getBytes());
                    if(verify){
                        // ServerHttpRequest token1 = exchange.getRequest().mutate().headers(httpHeaders -> {
                        //     httpHeaders.add("token1", token);
                        // }).build();
                        // ServerWebExchange exchange1 = exchange.mutate().request(token1).build();
                        return chain.filter(exchange);
                    }else{
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            }
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }

    public  String getToken(ServerHttpRequest request){
        String token = request.getHeaders().getFirst("token");
        return token;
    }
}
